#include("/admin/common/header.html")
#include("/admin/common/footer.html")
#include("/admin/common/left.html")
#include("/admin/common/layout.html")
 
 #@layout()
 #define content()

<span class="layui-breadcrumb">
  <a href="#(ctx_path)/">首页</a>
  <a href="#(ctx_path)/admin/shop/product"><cite>商品管理</cite></a>
</span>

<hr>


<form class="layui-form">
	<!-- 提示：如果你不想用form，你可以换成div等任何一个普通元素 -->

	<input type="hidden" name="id" value="#(vo.id)">
	<input type="hidden" name="files" value="">
	<input type="hidden" name="categoryId" value="#(vo.categoryId)">

	<div class="layui-card">
		<div class="layui-card-header">基本信息</div>
		<div class="layui-card-body">
			
			<div class="layui-form-item">
				<div class="layui-inline" id="treeSelect" >
					<label class="layui-form-label">商品类别</label>
				</div>
			</div>

			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">型号(名称)</label>
					<div class="layui-input-inline">
						<input type="text" name="name" autocomplete="off" value="#(vo.name)" class="layui-input">
					</div>
			  	</div>
			</div>

		</div>
			
	</div>

	<div class="layui-card">
		<div class="layui-card-header">商品价格<font color='red'></font></div>
		<div class="layui-card-body">
			
			<div  id="skuAttrDiv">

				#for(attr:attrs)

					<div class="layui-form-item">
						<label class="layui-form-label">
							#if(vo.id==null)
							<button class="layui-btn layui-btn-danger layui-btn-xs" type="button" onclick="delTemplate(this);">移除</button>
							#end
							#(attr.name)
							<input type='hidden' name='attrid' value='#(attr.id)'  title="#(attr.name)" />
						</label>
						<div class="layui-input-block">
				
	
							#set(pAttr={})
							#for(pAttrT:vo.pAttrs)
								#if(pAttrT.attrId==attr.id)
									#set(pAttr=pAttrT)
								#end
							#end
	
							#for(attrValue:attr.attrValues)
	
								#set(checkFlag=false)
	
								#for(pValue:pAttr.pAttrValues)
									#if(pValue.attrValueId==attrValue.id)
										#set(checkFlag=true)
									#end
								#end
	
								<input type="checkbox" name="#(attr.id)" #(checkFlag?'checked':'')
									lay-skin="primary" title="#(attrValue.value)" value="#(attrValue.id)">
							#end
				
						</div>
					</div>
				#end
			</div>

			<div>
				<button class="layui-btn" type="button" onclick="initSkuTable();">生成SKU信息</button>
			</div>
			<hr>
			<div id="skuAttrTable">

					<table class="layui-table" lay-size="sm">
					
						<thead>
							<tr>
								
								<th width="60px">&nbsp;</th>
								#for(pAttr:vo.pAttrs)
								<th>#(pAttr.name)</th>
								#end
				
								<th width="160px">货号</th>
								<th width="120px">库存</th>
								<th width="120px">价格</th>
							</tr>
						</thead>
						<tbody>
							#for(pSku:vo.pSkus)
							<tr>
								<td>
									<input type="hidden" name="skuId" value="#(pSku.id)">
									<button class="layui-btn layui-btn-danger layui-btn-xs"  type="button" onclick="delTemplate3(this);">删除</button>
								</td>
								#for(pAttr:vo.pAttrs)

									#set(pAttrValue={})

									#for(pAttrValueT:pAttr.pAttrValues)
										#for(pAttrGroup:pSku.pAttrGroups)
											#if(pAttrGroup.pAttrId==pAttr.id&&pAttrGroup.pAttrValueId==pAttrValueT.id)
												#set(pAttrValue=pAttrValueT)
											#end
										#end
									#end
									
									<td>
										<input type="hidden" name="#(pAttr.attrId)_sku_attrId" value="#(pAttrValue.attrValueId)">
										#(pAttrValue.value)
									</td>

								#end
								<td>
									<input type="text" name="skuCode" value="#(pSku.code)" placeholder="" autocomplete="off" class="layui-input" lay-verify="">
								</td>
								<td>
									<input type="text" name="skuStock" value="#(pSku.stock)" placeholder="必填" autocomplete="off" class="layui-input" lay-verify="required|number">
								</td>
								<td> 
									<input type="text" name="skuPrice" value="#(pSku.price)" placeholder="￥必填" autocomplete="off" class="layui-input" lay-verify="required|number">
								</td>
							</tr>
							#end
						</tbody>
					</table>

			</div>

		</div>
	</div>

	<div class="layui-card">
		<div class="layui-card-header">
			商品规格
			<button class="layui-btn layui-btn-xs" type="button" onclick="initExtAttr();">
				<i class="layui-icon layui-icon-add-1"></i>添加&nbsp;&nbsp;
			</button>
		</div>
		<div class="layui-card-body" id="extAttrBody">
			
			#for(ext_attr:vo.detailObj.ext_attr)

				<div class="layui-form-item">

					<div class="layui-inline">
						<label class="layui-form-label">
							<button class="layui-btn layui-btn-danger layui-btn-xs"  type="button" onclick="delTemplate2(this);">删除</button>
						</label>
						<div class="layui-input-inline" style="width: 300px;">
							<input type="text" name="ext_attr_name" value="#(ext_attr.ext_attr_name)" placeholder="属性名" autocomplete="off" class="layui-input">
						</div>
						<div class="layui-form-mid">:</div>
						<div class="layui-input-inline" style="width: 350px;">
							<input type="text" name="ext_attr_value" value="#(ext_attr.ext_attr_value)" placeholder="属性值" autocomplete="off" class="layui-input">
						</div>
					</div>
			
				</div>

			#end

		</div>
	</div>

	<div class="layui-card">
		<div class="layui-card-header">图文信息（目前主流模式都是图片，所以暂时支持图片）</div>
		<div class="layui-card-body">
			
			<style>

				.layui-upload-img {
					width: 92px;
					height: 92px;
					margin: 0 10px 10px 0;
				}
			</style>

			<div class="layui-upload">
				<button type="button" class="layui-btn" id="btnImage" lay-data="{fileType:'1'}">选择图片</button>
				<div class="layui-upload-list" id="uploadImages" style="margin-top: 10px;">

					#for(ext_img:vo.detailObj.ext_img)
						<img src="#(ctx_path)/file/#(ext_img.id)" index="#(ext_img.id)" fileid="#(ext_img.id)"
							alt="#(ext_img.originalFileName)" class="layui-upload-img" ondblclick="delFile(this)" title="双击删除图片">
					#end

				</div>
			</div>

			
		</div>
	</div>

	<div class="layui-form-item">
		<div class="layui-input-block">
			<button class="layui-btn" lay-submit lay-filter="detailForm">保存</button>
			<button type="reset" class="layui-btn layui-btn-primary">重置</button>
		</div>
	</div>
	


</form>


<script id="template" type="text/html" style="display: none;">

	<div class="layui-form-item">
		<label class="layui-form-label">
			<button class="layui-btn layui-btn-danger layui-btn-xs" type="button" onclick="delTemplate(this);">移除</button>
			{{d.name}}
			<input type='hidden' name='attrid' value='{{d.id}}' title="{{d.name}}" />
		</label>
		<div class="layui-input-block">

			{{# 
				layui.each(d.attrValues, function(index, item){ 
			}}
				<input type="checkbox" name="{{d.id}}" lay-skin="primary" title="{{item.value}}" value="{{item.id}}"> 
			{{# 
				});
			}}

		</div>
	</div>

</script>

<script id="template2" type="text/html" style="display: none;">

	<div class="layui-form-item">

		<div class="layui-inline">
			<label class="layui-form-label">
				<button class="layui-btn layui-btn-danger layui-btn-xs"  type="button" onclick="delTemplate2(this);">删除</button>
			</label>
			<div class="layui-input-inline" style="width: 300px;">
				<input type="text" name="ext_attr_name" placeholder="属性名" autocomplete="off" class="layui-input">
			</div>
			<div class="layui-form-mid">:</div>
			<div class="layui-input-inline" style="width: 350px;">
				<input type="text" name="ext_attr_value" placeholder="属性值" autocomplete="off" class="layui-input">
			</div>
		</div>

	</div>

</script>

<script id="template3" type="text/html" style="display: none;">

	<table class="layui-table" lay-size="sm">
				
		<thead>
			<tr>
				
				<th width="60px">&nbsp;</th>

				{{# 
					layui.each(d.attrs, function(index, item){ 
				}}
					<th>{{item.title}}</th>
				{{# 
					});
				}}

				<th width="160px">货号</th>
				<th width="120px">库存</th>
				<th width="120px">价格</th>
			</tr>
		</thead>
		<tbody>
			<!--下面的笛卡尔积算法算法参照https://blog.csdn.net/judyfun/article/details/50540400-->
			{{# 
				var xyz=[];
				var counter=[];
				var attrTotal=1;
				layui.each(d.attrs, function(index, attr){
					var attrValues=attr.attrValues;
					xyz.push(attrValues);
					counter.push(0);
					attrTotal*=attrValues.length;
				});
				var counterIndex=xyz.length-1;

				var handle=function(){
					counter[counterIndex]++;
					if (counter[counterIndex] >= xyz[counterIndex].length) {  
						counter[counterIndex] = 0;  
						counterIndex--;  
						if (counterIndex >= 0) {  
							handle();
						}  
						counterIndex = xyz.length - 1;  
					}  
				};

				for(var i=0;i < attrTotal;i++){
			}}
				<tr>
					<td>
						<input type="hidden" name="skuId" value="">
						<button class="layui-btn layui-btn-danger layui-btn-xs"  type="button" onclick="delTemplate3(this);">删除</button>
					</td>
			{{# 
				layui.each(d.attrs, function(index, item){ 
			}}
					<td>
						<input type="hidden" name="{{item.attrid}}_sku_attrId" value="{{xyz[index][counter[index]].id}}">
						{{xyz[index][counter[index]].title}}
					</td>
			{{# 
				});
			}}

					<td>
						<input type="text" name="skuCode" placeholder="" autocomplete="off" class="layui-input" lay-verify="">
					</td>
					<td>
						<input type="text" name="skuStock" placeholder="必填" autocomplete="off" class="layui-input" lay-verify="required|number">
					</td>
					<td> 
						<input type="text" name="skuPrice" placeholder="￥必填" autocomplete="off" class="layui-input" lay-verify="required|number">
					</td>
				</tr>
			{{# 
					handle();

				}

			}}

			
		</tbody>
	</table>
		

</script>

#end

#define js()

<script>

	var uploadInst;
	var files = [];
	function delFile(obj){
		$(obj).remove();
	}

	function doSubmit(){

		layer.confirm("<font color='red'>请注意：</font><br/>保存后,为防止商品编辑错误，该商品处于下架状态，需手动上架", function(index){
			
			//先处理文件
			var files="";
			$("#uploadImages").find("img").each(function(){
				files+=$(this).attr("fileid")+",";
			});
			$(":input[name='files']").val(files);

			$.ajax({
				type : 'post',
				url : '#(ctx_path)/admin/shop/product/save',
				data : $("form").serialize(),
				success : function(data) {
					if (data.code == "0") {
						layer.msg('保存成功！', {
							time : 600
						}, function() {
							window.location.href = "#(ctx_path)/admin/shop/product";
						});
					}
				}
			});

			layer.close(index);
		});   

	}

	layui.use(['table','upload'], function() {
		var form = layui.form;
		var $ = layui.$;
		var layer = layui.layer;
		var upload = layui.upload;

		uploadInst=upload.render({
			elem: '#btnImage',
			url: '#(ctx_path)/file/upload',
			accept:'images',
			acceptMime:'image/*',
			auto:false,
			multiple: true ,
			number:15,//最大15个文件
			size:1024*6,//最大文件10M,
			choose: function(obj){

				var files = obj.pushFile();

				//预读本地文件示例，不支持ie8
				obj.preview(function(index, file, result){
					console.log(file);
					var html='<img src="'+ result +'" index="'+index+'" alt="'+ file.name +'" class="layui-upload-img" ondblclick="delFile(this)" title="双击删除图片">';
					$('#uploadImages').append(html);
				});
			},
			done: function(res, index, upload){

				//单个文件上传完毕
				if(res.code=="0"){
					var data=res.data;
					
					if(this.fileType=="1"){
						var imgIndex=$("#uploadImages").find("img[index='"+index+"']");
						if(imgIndex.length>0){
							imgIndex.attr("fileid",data.id);
						}
					}else if(this.fileType=="2"){

					}

				}
			},
			allDone: function(obj){ //当文件全部被提交后，才触发
				// console.log(obj.total); //得到总文件数
				// console.log(obj.successful); //请求成功的文件数
				// console.log(obj.aborted); //请求失败的文件数
				
				doSubmit();//文件全部上传完成，然后提交表单
			}
		});

		console.log(uploadInst);

		//对自定义的表单进行验证
		form.verify(layuiFormVerify);

		form.on('submit(detailForm)', function(data) {
			//建议使用ajax在此处提交。
			

			//特殊认证，认证加在此处，否则表单会自动跳转
			var val=$("#treeSelect").find(".layui-treeSelect:last").find("select").val();
			if(val==""){
				layer.msg('请选择商品类别', {
					time : 3000
				}, function() {
					
				});
				return false;
			}
			$(":input[name='categoryId']").val(val);

			//此处需要判断下，如果没有需要上传的文件，那么直接doSubmit();上传控件如果增加一个完成的回调事件就好了，就不用再此处判断了
			var notUploadImages=$("#uploadImages").find("img:not([fileid])");
			if(notUploadImages.length>0){
				uploadInst.upload();
			}else{
				doSubmit();//没有文件上传，直接提交表单
			}

			//此处使用异步的好处，服务器端可以直接验证，如果直接提交，提交完成以后，如果验证不通过，那么不方便处理错误的信息
			return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
		});

	});


	function initAttr(data){
		$.ajax({
			type:'get',
			url:'#(ctx_path)/admin/product/getAttrByCategory',
			data:'categoryId='+data.value,
			success:function(rep){
				if(rep.code=='0'){

					var data=rep.data;
					var attrHtml="";
					for(var i=0;i<data.length;i++){
						layui.laytpl($("#template").html()).render(data[i], function(html){
							attrHtml+=html;
						});
					}
					$("#skuAttrDiv").html(attrHtml);
					layui.form.render();

				}
			}
		});
	}

	function delTemplate(obj){
		layer.confirm('确认移除么?', function(index){
			$(obj).parent().parent().remove();
			layer.close(index);
		});   
	}

	function initExtAttr(){
		var attrHtml="";
		layui.laytpl($("#template2").html()).render({}, function(html){
			attrHtml+=html;
		});
		$("#extAttrBody").append(attrHtml);
		layui.form.render();
		
	}

	function delTemplate2(obj){
		//因为属性可以继续添加，所以删除不需要提醒
		$(obj).parent().parent().remove();
	}

	function delTemplate3(obj){
		//因为属性可以继续添加，所以删除不需要提醒
		$(obj).parent().parent().remove();
	}

	var nodes=[];

	function initTree(){
		$("#treeElem").html("");
		$.ajax({
			type:'get',
			url:'#(ctx_path)/admin/shop/category/tree',
			data:'',
			success:function(data){
				if(data.code=='0'){

					nodes=data.data;
					
					var categoryId=$(":input[name='categoryId']").val();
					if(categoryId){
						initForm(categoryId);
					}else{
						initForm();
					}

				}
			}
		});
	}

	function initForm(categoryId){
		var disabled=false;
		if(categoryId){
			disabled=true;
		}
		layui.use('treeSelect',function(){
			var treeSelect=layui.treeSelect;
			treeSelect.init("#treeSelect",{
				nodes:nodes,
				data:categoryId,
				disabled:disabled,
				selectCallback:function(data){
					initAttr(data);//选中以后初始化属性
				}
			});
		});
		
	}


	function initSkuTable(){

		var initAction=function(){
			var skuTablehtml="";

			var attrs=[];
			$(":input[name='attrid']").each(function(i){
				var attr={};
				var attrValues=[];

				attr.attrid=$(this).val();
				attr.title=$(this).attr("title");

				$(":input[name='"+attr.attrid+"']:checked").each(function(j){
					var attrValue={};
					attrValue.id=$(this).val();
					attrValue.title=$(this).attr("title");
					attrValues.push(attrValue);
				});

				
				attr.attrValues=attrValues;

				attrs.push(attr);
			});


			var attrids=$(":input[name='attrid']");
			for(var i=0;i<attrids.length;i++){
				var attr={};
				var attrid=attrids
			}

			var data={
				attrs:attrs
			};

			layui.laytpl($("#template3").html()).render(data, function(html){
				skuTablehtml+=html;
			});
			$("#skuAttrTable").html(skuTablehtml);
		}

		layer.confirm('确认SKU信息么？', function(index){
			initAction();
			layer.close(index);
		});

	}



	$(function(){
		initTree();
	});

</script>

#end


